package com.shanghaionstar.joinme;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;

import com.onstar.cn.api.JoinmeInfo3Service;
import com.onstar.cn.api.JoinmeService;
import com.onstar.cn.common.exception.HttpException;
import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.DeviceUtil;

import com.onstar.cn.common.util.MyPost;
import com.onstar.cn.framework.annotation.http.HeadsValue;
import com.onstar.cn.framework.annotation.http.Request;
import com.onstar.cn.framework.network.entity.RequestEntity;
import com.onstar.cn.framework.network.enumtype.HttpAccept;
import com.onstar.cn.framework.network.enumtype.HttpMethod;
import com.onstar.cn.framework.network.enumtype.Language;
import com.onstar.cn.framework.network.http.ResponseHandler;
import com.onstar.cn.framework.network.http.Sender;
import com.onstar.cn.framework.utils.GsonHelper;
import com.onstar.cn.mag.enumtype.SendCodeSenarioType;
import com.onstar.cn.mag.joinme.RegisterRequestEntity;
import com.onstar.cn.mag.joinme.RegisterToVisitorResponse;
import com.onstar.cn.vehicle.entity.ErrorEnum;
import com.onstar.cn.vehicle.entity.ErrorInfo;
import com.shanghaionstar.R;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.AuthorUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.ErrorCodeUtil;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.NetConnectUtil;

import java.util.LinkedHashMap;
import java.util.Locale;

/**
 * Created by 6335yz on 2016/7/1.
 */
public class JoinMeUtil {
    private ProgressDialog dialog;
    private LogManager log = LogManager.getInstance();

    private Context context;
    private String vin;
    private String govID;
    private String captchaId;
    private String captchaValuse;
    private boolean required;
//	public JoinMeUtil(context context, boolean isMore) {
//		this.context = context;
//		this.isMore = isMore;
//	}
    /**
     *
     * @Description: 从maintabcontext 转为context，这样无法在注册后跳到主页
     * @author zengshuai shi
     * @date 2015年11月3日 上午9:45:44
     */
    public JoinMeUtil(Context context, boolean isMore) {
        this.context = context;
    }

    /**
     *
     * @Description: 给升级为车主使用
     * @author 6335yz
     * @date 2015年10月26日 下午9:51:02
     */
    public JoinMeUtil(Context context, String vin, String govID) {
        this.context = context;
        this.govID = govID;
        this.vin = vin;
    }

    public JoinMeUtil(Context context, String vin, String govID, String captchaId, String captchaValuse, boolean required) {
        this.context = context;
        this.govID = govID;
        this.vin = vin;
        this.captchaId = captchaId;
        this.captchaValuse = captchaValuse;
        this.required = required;
    }


    /**
     * Check visitor are there permission upgrade
     *
     * @param
     */
    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO) , method = HttpMethod.PUT)
    public void checkVisitor(final boolean isFromJoinmecontext) {
		/*
		 * ReportBusiness reportBusiness = ReportBusiness.getInstance(tabcontext);
		 * reportBusiness.operateReport(FunctionNameFindId.Upgrade_Subscriber,
		 * OperateType.CLICK,
		 * ReportBusiness.getDateFromPattern(ReportBusiness.pattern),
		 * Constants.isLoggedIn);
		 */
//        BusinessUtil.sendReportByClickType(context, FunctionNameFindId.Upgrade_Subscriber.getStringValue());
        dialog = new ProgressDialog(context);
        dialog.setTitle(context.getResources().getString(R.string.sendingRequest));
        dialog.setMessage(context.getResources().getString(R.string.waiting));
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();

        JoinmeService joinmeService = new JoinmeService(Constants.CURRENT_SERVER_URL);
        JoinmeInfo3Service joinmeService1 = new JoinmeInfo3Service(Constants.CURRENT_SERVER_URL);
//		JoinmeService joinmeService = new JoinmeService("http://10.16.138.52:8080");
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        RegisterRequestEntity entity = new RegisterRequestEntity();
        entity.setUserName(ApplicationUtil.getInstance().getIdpID());
        entity.setSendCodeSenario(SendCodeSenarioType.SUB_TO_VISITOR.value());
        entity.setLanguageId(DeviceUtil.getLanguage().toUpperCase(Locale.CHINA).equals("ZH") ? "CN" : DeviceUtil.getLanguage()
                .toUpperCase(Locale.CHINA));

        if(isFromJoinmecontext) {
            entity.setGovernmentID(govID);
            entity.setVin(vin);
        }
        if(required){//升级为车主的时候判断是否需要添加验证码id和value
            entity.setCaptchaId(captchaId);
            entity.setCaptchaValue(captchaValuse);
        }
        entity.setSourceId(new DeviceUtil(context).getDeviceID());
        LinkedHashMap<String, Object> customHeads = new LinkedHashMap<String, Object>();
        customHeads.put(FinalConstants.DEVICE_ID, new DeviceUtil(context).getDeviceID());
        customHeads.put(FinalConstants.HTTP_AUTHORIZATION, ApplicationUtil.getInstance().getToken());
        requestEntity.setCustomHeads(customHeads);
        requestEntity.setBody(GsonHelper.toJson(entity));
        requestEntity = joinmeService1.registerToUpgrade(requestEntity, entity);
        new Sender().send(requestEntity, new ResponseHandler() {
            @Override
            public void onSuccess(String tag, String json) {
                log.d("upgrade to subscriber --->"+json);
                try {
                    RegisterToVisitorResponse res = GsonHelper.fromJson(json,RegisterToVisitorResponse.class);
                    final String bbwcMsg = res.getBbwcMessage();
                    ErrorInfo errorInfo = res.getErrorInfo();
                    if (errorInfo != null && !errorInfo.getCode().equalsIgnoreCase(ErrorEnum.SB021_MSG000.getStringValue())) {
                        showErrorMessage(errorInfo);
                    } else {
                        BusinessUtil.updateConfigValue("UPGRADE_OWNER", "true", context);
                        MyPost.post(new Runnable() {
                            @Override
                            public void run() {
                                if (dialog != null && dialog.isShowing()) {
                                    dialog.dismiss();
                                }
                                if(isFromJoinmecontext) {//从joimmevin页面进入
                                    AlertDialogUtil.showAlertDialog(context, context.getString(R.string.dialog_warning), bbwcMsg, new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            AuthorUtil.getInstance().loginOut(context);
//                                            Intent intent = new Intent(context, Logincontext.class);
//                                            context.startcontext(intent);
//                                            context.finish();
                                        }
                                    });
                                }else {
//                                    Intent intent = new Intent(context, JoinMeVincontext.class);
//                                    intent.putExtra("isUpgradeToSub", true);
//                                    context.startcontextForResult(intent, Constants.REQ_CODE_JOINME);
                                }
                            }
                        });
                    }
                } catch (Exception e) {
                    ErrorInfo errorInfo = BusinessUtil.getErrorInfoByException(context, e);
                    showErrorMessage(errorInfo);
                }
            }

            @Override
            public void onError(String tag, HttpException e) {
                log.e(e.getMessage());
//				ErrorInfo errorInfo = BusinessUtil.getErrorInfoByException(context, e);
                ErrorInfo errorInfo = ErrorCodeUtil.getErrorInfoByHttpException(context, e);
                showErrorMessage(errorInfo);
            }
        }, getClass(), "checkVisitor", boolean.class);
    }

    /**
     * Show error message
     *
     * @param errorInfo
     */
    private void showErrorMessage(final ErrorInfo errorInfo) {
        MyPost.post(new Runnable() {
            @Override
            public void run() {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                AlertDialogUtil.showAlertDialog(context, context.getString(R.string.dialog_warning), errorInfo.getMessageDetail());
            }
        });
    }
}
